package com.itheima03.day15Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 刘全
 * @date 2021/8/9
 */
public class Lock implements Runnable {
    private int count = 50;
    private ReentrantLock rl = new ReentrantLock();

    @Override
    public void run() {
        //while(true)外面不能放rl.lock(),因为对共享数据进行操作是在if判断开始的
        //rl.lock();
        while (true) {
            try {
                rl.lock();
                if (count == 0) {
                    break;
                } else {
                    Thread.sleep(20);
                    count--;
                    System.out.println(Thread.currentThread().getName() + "在卖票,还剩" + count + "张票");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                rl.unlock();
            }
            //此处如果没有用try catch finally的话程序运行不会结束
            //rl.unlock();
        }
        //rl.unlock();
    }
}
